package boun.swe.bob.dao;

import boun.swe.bob.entities.User;
import boun.swe.bob.entities.UserAction;
import boun.swe.bob.entities.UserTweet;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * This DAO corresponds to user_actions table in database
 */
@Component
public class UserActionDao extends GenericDaoImpl<UserAction, Integer>{

    private static final Logger LOG = Logger.getLogger(UserActionDao.class);

    /**
     * This method gets the last user action in the table
     *
      * @param userId Users Id
     * @return the record
     */
    public UserAction findLastInsertedUserAction(final int userId) {
        return (UserAction) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select max(action_id) from user_actions where user_id = ?");
                query.setInteger(0, userId);
                Integer id = (Integer) query.uniqueResult();
                query = session.createSQLQuery("select * from user_actions where action_id = ?").addEntity(UserAction.class);
                query.setInteger(0, id);
                return query.uniqueResult();
            }
        });
    }


}
